package com.sctvcloud.bazhong.ui.dialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseBottomSheetFrag;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.application.Constances;
import com.sctvcloud.bazhong.beans.SingleResult;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.DMethods;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.http.ParamsEditor;
import com.sctvcloud.bazhong.ui.activities.LoginActivity;
import com.sctvcloud.bazhong.ui.activities.SpeakActivity;
import com.sctvcloud.bazhong.ui.utils.KeyBoardUtils;
import com.sctvcloud.bazhong.utils.UserManager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/7/25 0025.
 */

public class CommentDiaFragment extends BaseBottomSheetFrag implements View.OnClickListener {
    private CustomFontEditText comment_ct;
    private ImageView voice;
    private CustomFontTextView send;
    private SendComment sendComment;
    private CustomFontTextView count;
    public static final int REQUEST_CODE_VOICE = 3;
    public static final int REQUEST_CODE_LOGIN = 5;

    private String newsId;
    private String commentId;
    private int commentType;
    private boolean isLuzhow = false;

    //    @Override
//    protected BottomSheetDialog creatBottomSheetDialog(Bundle savedInstanceState) {
//        BottomSheetDialog dialog = new BottomSheetDialog(getActivity(), R.style.BottomDialog);
//        Window window = dialog.getWindow();
//        dialog.setCanceledOnTouchOutside(true);// 外部点击取消
////        WindowManager.LayoutParams params = window.getAttributes();
////        params.gravity = Gravity.BOTTOM;
////        params.width = WindowManager.LayoutParams.MATCH_PARENT;
////        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
////        window.setAttributes(params);
////        window.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
//        return dialog;
//    }
    private int types;

    public int getTypes() {
        return types;
    }

    public void setTypes(int types) {
        this.types = types;
    }

    public boolean isLuzhow() {
        return isLuzhow;
    }

    public void setLuzhow(boolean luzhow) {
        isLuzhow = luzhow;
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int length = getStrLength(s.toString());
            count.setText(getString(R.string.comment_litmit_, length));
            if (length > 500) {
                toast(R.string.only_500_word);
            }

        }
    };

    @Override
    public int getLayoutResId() {
        return R.layout.dia_comment_fragment;
    }

    public void setCommentType(int commentType) {
        this.commentType = commentType;
    }

    public SendComment getSendComment() {
        return sendComment;
    }

    public CommentDiaFragment setSendComment(SendComment sendComment) {
        this.sendComment = sendComment;
        return this;
    }

    public void onLoginSuc() {
        send.callOnClick();
    }

    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(this.getClass().getName(), ex.toString());
        }
        return null;
    }


    @Override
    public void initView() {
        comment_ct = (CustomFontEditText) rootView.findViewById(R.id.dia_comment_fragment_write_comment);
        voice = (ImageView) rootView.findViewById(R.id.dia_comment_fragment_voice);
        send = (CustomFontTextView) rootView.findViewById(R.id.dia_comment_fragment_write_send);
        count = (CustomFontTextView) rootView.findViewById(R.id.comment_fragment_count);
        send.setOnClickListener(this);
        voice.setOnClickListener(this);
        comment_ct.addTextChangedListener(watcher);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onClick(View v) {
        if (isLuzhow) {
            toast(R.string.cannot_input_comment);
            return;
        }
        if (v == send) {
            String str = comment_ct.getText().toString();
            if (TextUtils.isEmpty(str)) {
                toast(R.string.please_input_comment);
                return;
            }
            sendComments(str);

            KeyBoardUtils.closeKeyboard(getActivity());
//            dismiss();
        } else if (v == voice) {
            Intent intent = new Intent(getActivity(), SpeakActivity.class);
            startActivityForResult(intent, REQUEST_CODE_VOICE);
        }
    }

    private int getStrLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }

    public interface SendComment {
        boolean onCommentSendPrepare(int mode);

        void onCommentSendSuccess(int mode);

        void onCommentSendFinish(int mode, boolean isNetSuc);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_VOICE) {
            if (data != null) {
                String voice = data.getStringExtra(SpeakActivity.SEARCH_KEY);
                if (!TextUtils.isEmpty(voice)) {
                    comment_ct.setText(voice);
                }
            }
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        comment_ct.removeTextChangedListener(watcher);
        comment_ct.setText("");
        super.onDismiss(dialog);
        commentId = null;
    }

    /**
     * 发送评论
     *
     * @param commentText 评论内容
     * @return
     */
    protected boolean sendComments(String commentText) {
        if (TextUtils.isEmpty(newsId)) {
            toast("数据错误");
            return false;
        }
        if (!UserManager.isLoginS()) {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivityForResult(intent, REQUEST_CODE_LOGIN);
//            commentTemp = new CommentTemp(newsId, commentId, commentText);
            return false;
        }
        boolean b = TextUtils.isEmpty(commentId);
        final int mode = b ? Constances.MODE_COMMENT_SEND_NEWS : Constances.MODE_COMMENT_SEND_COMMENT;
        if (sendComment != null && !sendComment.onCommentSendPrepare(mode)) {
            return false;
        }
        showProgress("正在发送评论...");
        ParamsEditor pe = new ParamsEditor();
        if (!b) {
//            commentId = "";
            pe.put("commentId", commentId);
        }
        pe.put("commentText", commentText);
        pe.put("commentType", commentType);
        String str = getLocalIpAddress();
        if (!TextUtils.isEmpty(str)) {
            pe.put("ip", str);
        }
        pe.put("siteNumber", Constances.SITE_ID);
        pe.put("sourceId", newsId);
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
//        ip = "192.168.23.225";
//        siteNumber = 1;
        String token = UserManager.getInstance().getToken();
        NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.Comment, pe.getEncryptedParams(token)
                , new AbsNetCallBack<SingleResult>(SingleResult.class) {
                    private boolean isSuc;

                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult != null && singleResult.isSuccess()) {
                            toast(R.string.comment_suc_wait);
                            if (sendComment != null) {
                                comment_ct.setText("");
                                sendComment.onCommentSendSuccess(mode);
                                closeProgress();
                                dismissAllowingStateLoss();
                            }
                        }
                        isSuc = true;
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        super.onError(ex, errorMsg, netCode);
                        closeProgress();
                        JLog.e("===errMsg==" + errorMsg);
                        toast(errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (sendComment != null) {
                            sendComment.onCommentSendFinish(mode, isSuc);
                        }
                    }
                });
        return true;
    }

    public void setInfo(String newsId, String commentId) {
        this.newsId = newsId;
        this.commentId = commentId;
    }
}
